package mwa.cs.hh.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import mwa.cs.dao.RouteDAO;
import mwa.cs.dao.RouteDetailDAO;
import mwa.cs.dao.ZoneDAO;
import mwa.cs.database.Database;

/**
 * Servlet implementation class ManageSequenceRouteDetailSrvl
 */
public class CS35000Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;
	private int vnZoneId;
	private int vnRouteId;
	private int vnSequenceNew;
	private int vnSequenceOld;
	private String vaAccount;
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CS35000Srvl() {
		super();
		// TODO Auto-generated constructor stub
	}

	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		if (request.getParameter("process_type").equals("edit")) {
			editSequence(request, response);
		} else if (request.getParameter("process_type").equals("getDataTable")) {
			getDataTable(request, response);
		} else if (request.getParameter("process_type").equals("getZone")) {
			getZone(request, response);
		} else  if (request.getParameter("process_type").equals("delete")) {
			deleteSequence(request, response);
		}else if (request.getParameter("process_type").equals("goToManageSequence")) {
			goToManageSequence(request, response);
		}

	}
	
	public void goToManageSequence(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int pnZoneId = Integer.parseInt(request.getParameter("zone_id"));
		int pnRouteId = Integer.parseInt(request.getParameter("route_id"));
		
		request.setAttribute("pnZoneId", pnZoneId);
		request.setAttribute("pnRouteId", pnRouteId);
		
		RequestDispatcher voRequestDispatcher = request
				.getRequestDispatcher("CS35000.jsp");
		voRequestDispatcher.forward(request, response);
	}
	public void editSequence(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		if (request.getParameter("vnZoneId") != null) {
			vnZoneId = Integer.parseInt(request.getParameter("vnZoneId"));
		} else {
			vnZoneId = -1;
		}
		if (request.getParameter("vnRouteId") != null) {
			vnRouteId = Integer.parseInt(request.getParameter("vnRouteId"));
		} else {
			vnRouteId = -1;
		}
		if (request.getParameter("vnSequenceNew") != null) {
			vnSequenceNew = Integer.parseInt(request
					.getParameter("vnSequenceNew"));
		} else {
			vnSequenceNew = -1;
		}
		if (request.getParameter("vnSequenceOld") != null) {
			vnSequenceOld = Integer.parseInt(request
					.getParameter("vnSequenceOld"));
		} else {
			vnSequenceOld = -1;
		}
		vaAccount = request.getParameter("vaAccount");
		Database db = new Database();
		RouteDetailDAO voRouteDetailDAO = new RouteDetailDAO(db);
		voRouteDetailDAO.updateSequenceRouteDetail(vnUserId, vnSiteId,
				vnZoneId, vnRouteId, vnSequenceNew, vnSequenceOld,
				vaAccount);

	}
	public void deleteSequence(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		if (request.getParameter("vnZoneId") != null) {
			vnZoneId = Integer.parseInt(request.getParameter("vnZoneId"));
		} else {
			vnZoneId = -1;
		}
		if (request.getParameter("vnRouteId") != null) {
			vnRouteId = Integer.parseInt(request.getParameter("vnRouteId"));
		} else {
			vnRouteId = -1;
		}
		vaAccount = request.getParameter("vaAccount");
		Database db = new Database();
		RouteDetailDAO voRouteDetailDAO = new RouteDetailDAO(db);
		voRouteDetailDAO.deleteSequenceRouteDetail(vnUserId, vnSiteId, vnZoneId, vnRouteId, vaAccount);
	}
	@SuppressWarnings("unchecked")
	public void getDataTable(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		if (request.getParameter("vnZoneId") != null) {
			vnZoneId = Integer.parseInt(request.getParameter("vnZoneId"));
		} else {
			vnZoneId = -1;
		}
		if (request.getParameter("vnRouteId") != null) {
			vnRouteId = Integer.parseInt(request.getParameter("vnRouteId"));
		} else {
			vnRouteId = -1;
		}
		
		boolean vbSearch = false;
		String vnZoneIdSearching = request.getParameter("sSearch_0").trim();
		String vnRouteIdSearching = request.getParameter("sSearch_1")
				.trim();

		if (!vnZoneIdSearching.equals("") && !vnRouteIdSearching.equals("")) {
			vnZoneId = Integer.parseInt(vnZoneIdSearching);
			vnRouteId = Integer.parseInt(vnRouteIdSearching);
			vbSearch = true;
		}
		String[] vaColumns = { "seq", "seq", "seq", "account", "fname",
				"seq" };
		int vnStart = Integer.parseInt(request
				.getParameter("iDisplayStart")); // 0
		int vnAmount = Integer.parseInt(request
				.getParameter("iDisplayLength")); // 10
		int vnSortColumn = Integer.parseInt(request
				.getParameter("iSortCol_0")); // 0, 1, 2, 3
		String vaSortDirection = request.getParameter("sSortDir_0"); // asc,
																		// desc

		Database db = new Database();
		RouteDetailDAO voRouteDetailDAO = new RouteDetailDAO(db);
		PrintWriter voOut = response.getWriter();
		List<Map<String, Object>> voList = new ArrayList<Map<String, Object>>();
		Map<String, Object> voMap = new HashMap<String, Object>();

		int vnTotalRecords = voRouteDetailDAO
				.getCountManageSequenceRouteDetail(vnSiteId, vnZoneId,
						vnRouteId);
		int vnTotalDisplayRecords = 0;

		int vnEnd = vnStart + vnAmount;

		if (vnAmount != -1 || vbSearch == true) {
			voList = voRouteDetailDAO
					.findManageSequenceRouteDetailByLength(vnSiteId,
							vnZoneId, vnRouteId, vaColumns[vnSortColumn],
							vaSortDirection, vnStart, vnEnd);
			vnTotalDisplayRecords = voRouteDetailDAO
					.getCountManageSequenceRouteDetailSearch(vnSiteId,
							vnZoneId, vnRouteId, vaColumns[vnSortColumn],
							vaSortDirection);
		}
		if (vnAmount == -1 || vbSearch != true) {
			voList = voRouteDetailDAO.findManageSequenceRouteDetail(
					vnSiteId, vnZoneId, vnRouteId, vaColumns[vnSortColumn],
					vaSortDirection);
			vnTotalDisplayRecords = vnTotalRecords;
		}
		
		JSONObject voObject = new JSONObject();
		JSONArray voListData = new JSONArray();
		JSONArray voArray = new JSONArray();
		JSONArray voSequence = new JSONArray();
		JSONArray voName = new JSONArray();
		for (int i = 0; i < voList.size(); i++) {
			voArray = new JSONArray();
			voMap = voList.get(i);
			voArray.add((String) "" + voMap.get("ACCOUNT"));
			voArray.add((String) "" + voMap.get("ZONE_NAME"));
			voArray.add((String) "" + voMap.get("ROUTE_DESCRIPTION"));
			voArray.add((String) "" + voMap.get("ACCOUNT"));
			voName = new JSONArray();
			voName.add(voMap.get("ACCOUNT"));
			voName.add(voMap.get("NAME"));
			voArray.add(voName);
			String vaOptions = "";
			for (int j = 1; j <= vnTotalRecords; j++) {

				if (j == Integer.parseInt("" + voMap.get("SEQ"))) {
					vaOptions += "<option value='" + j
							+ "' selected='selected'>" + j + "</option>";
				} else {
					vaOptions += "<option value='" + j + "'>" + j
							+ "</option>";
				}

			}
			voSequence = new JSONArray();
			voSequence.add("" + voMap.get("ACCOUNT"));
			voSequence.add("" + voMap.get("SEQ"));
			voSequence.add("" + vaOptions);
			voArray.add(voSequence);
			voListData.add(voArray);
		}

		voObject.put("iTotalRecords", vnTotalRecords);
		voObject.put("iTotalDisplayRecords", vnTotalDisplayRecords);
		voObject.put("aaData", voListData);
		voOut.print(voObject.toJSONString());
	}
	@SuppressWarnings("unchecked")
	public void getZone(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String vaZone = request.getParameter("zone");
		String vaRoute = request.getParameter("route");
		Database db = new Database();
		PrintWriter voOut = response.getWriter();
		String[] vaMessage = null, vaValue = null;
		if (vaZone != null && vaZone.equals("yes")) {
			ZoneDAO voZone = new ZoneDAO(db);
			List<Map<String, Object>> voResult = voZone
					.findZoneBySite(vnSiteId);
			vaValue = new String[voResult.size()];
			vaMessage = new String[voResult.size()];
			for (int i = 0; i < voResult.size(); i++) {
				Map<String, Object> voObject = voResult.get(i);
				vaValue[i] = ((BigDecimal) voObject.get("ZONE_ID"))
						.toString();
				vaMessage[i] = (String) voObject.get("ZONE_NAME");
			}
		} else if (vaRoute.equals("yes")) {
			RouteDAO voRoute = new RouteDAO(db);
			int vnZoneId = Integer
					.parseInt(request.getParameter("zone_id"));
			List<Map<String, Object>> voResult = voRoute.findRouteByZone(
					vnSiteId, vnZoneId);
			vaValue = new String[voResult.size()];
			vaMessage = new String[voResult.size()];
			for (int i = 0; i < voResult.size(); i++) {
				Map<String, Object> voObject = voResult.get(i);
				vaValue[i] = ((BigDecimal) voObject.get("ROUTE_ID"))
						.toString();
				vaMessage[i] = (String) voObject.get("ROUTE_DESCRIPTION");
			}
		}
		db.close();
		JSONObject voObject = new JSONObject();
		JSONArray voList = new JSONArray();
		if (vaMessage != null) {
			for (int i = 0; i < vaMessage.length; i++) {
				voList.add(vaMessage[i]);
			}
		}
		voObject.put("messages", voList);
		JSONArray voList2 = new JSONArray();
		if (vaValue != null) {
			for (int i = 0; i < vaValue.length; i++) {
				voList2.add(vaValue[i]);
			}
		}
		voObject.put("values", voList2);
		voOut.print(voObject.toJSONString());
	}
	

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
